package cn.picclife.mwx.manager.sys.service.impl;

import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;

import cn.picclife.mwx.manager.sys.controller.QualityDataController;
import cn.picclife.mwx.manager.sys.mapper.ArchiveMapper;
import cn.picclife.mwx.manager.sys.mapper.DataCollectMapper;
import cn.picclife.mwx.manager.sys.mapper.SysMaintainMapper;
import cn.picclife.mwx.manager.sys.model.bo.ArchiveBo;
import cn.picclife.mwx.manager.sys.model.bo.ArichiveRet;
import cn.picclife.mwx.manager.sys.model.bo.DataResponse;
import cn.picclife.mwx.manager.sys.model.bo.PageCount;
import cn.picclife.mwx.manager.sys.model.bo.PathBo;
import cn.picclife.mwx.manager.sys.model.bo.QueryDataCollectListRes;
import cn.picclife.mwx.manager.sys.model.bo.UpdateCollectReq;
import cn.picclife.mwx.manager.sys.model.po.Archive;
import cn.picclife.mwx.manager.sys.model.po.DataCollect;
import cn.picclife.mwx.manager.sys.model.po.SysMaintain;
import cn.picclife.mwx.manager.sys.service.IArchiveService;
import cn.picclife.mwx.manager.util.LogUtil;
import cn.picclife.mwx.manager.util.enums.ResponseStatusEnum;

/**
 * 归档管理
 * @author Administrator
 *
 */
@Service
public class ArchiveServiceImpl implements IArchiveService {
	
	@Autowired
	private ArchiveMapper mapper;
	
	@Autowired
	public DataCollectMapper dataCollectMapper;

	@Autowired
	public SysMaintainMapper sysMaintainMapper;
	
	private Log log = LogFactory.getLog(QualityDataController.class);

	@Override
	public DataResponse insertArchive(ArchiveBo bo) throws Exception {
		DataResponse response = new DataResponse();
		if(bo == null){
			response.setCode(ResponseStatusEnum.PARAM_IS_NULL.getCode());
			response.setMsg(ResponseStatusEnum.PARAM_IS_NULL.getName());
			return response;
		}
		if(bo.getArchiveDir() == null || "".equals(bo.getArchiveDir().trim())){
			response.setCode(ResponseStatusEnum.FAIL_CODE.getCode());
			response.setMsg(ResponseStatusEnum.FAIL_CODE.getName() + "：archiveDir不能为空");
			return response;
		}
		if(bo.getArchiveTime() == null || "".equals(bo.getArchiveTime().trim())){
			response.setCode(ResponseStatusEnum.FAIL_CODE.getCode());
			response.setMsg(ResponseStatusEnum.FAIL_CODE.getName() + "：archiveTime不能为空");
			return response;
		}
		if(bo.getEndArchiveTime() == null || "".equals(bo.getEndArchiveTime().trim())){
			response.setCode(ResponseStatusEnum.FAIL_CODE.getCode());
			response.setMsg(ResponseStatusEnum.FAIL_CODE.getName() + "endArchiveTime不能为空");
			return response;
		}
		Archive archive = new Archive();
		archive.setArchiveDir(bo.getArchiveDir());
		archive.setArchiveTime(bo.getArchiveTime());
		archive.setEndArchiveTime(bo.getEndArchiveTime());
		try {
			List<Archive> list = mapper.queryAllData();
			if(list != null && !list.isEmpty()){
				mapper.updateData(archive);
			}else{
				mapper.saveData(archive);
			}
			response.setCode(ResponseStatusEnum.SUCCESS_CODE.getCode());
			response.setMsg(ResponseStatusEnum.SUCCESS_CODE.getName());
		} catch (Exception e) {
			LogUtil.error(ResponseStatusEnum.EXCEPTION.getName(), e);
			response.setCode(ResponseStatusEnum.EXCEPTION.getCode());
			response.setMsg(ResponseStatusEnum.EXCEPTION.getName() + "；" + e.getMessage());
		}
		return response;
	}

	@Override
	public DataResponse getAllArchive(){
		DataResponse response = new DataResponse();
		try {
			List<Archive> list = mapper.queryAllData();
			String url = list.get(0).getArchiveDir();
//			List<PathBo> ts = (List<PathBo>) JSONArray.parseArray(url, PathBo.class);
//			List<Map<String,Object>> retList =new LinkedList<>();
			ArichiveRet ArichiveRet =new ArichiveRet();			
			String path = url;
			/*for(PathBo bo :ts) {
				String allPath = bo.getPath();
				path = allPath.substring(allPath.indexOf("dev/")+4);
				path = path.substring(path.indexOf("/"),path.length());
//				path=allPath.substring(allPath.length());
//				String disk = allPath.substring(0,allPath.indexOf("dev/"));
//				path = allPath.substring(allPath.indexOf("dev/")+4,allPath.length());
//				Integer rate = diskPre(disk);
//				Map<String,Object> retMap = new HashMap<>();
//				retMap.put("apath", disk);
//				retMap.put("space", rate+"%");
//				retList.add(retMap);		
				Runtime rt = Runtime.getRuntime();
	            Process p = rt.exec("df -hl");// df -hl 查看硬盘空间
	            List<String> result = IOUtils.readLines(p.getInputStream(), "GBK");
	            for (String line: result) {         	
	            	String deskName= allPath.substring(0,allPath.indexOf("dev/")+4);           	              
	                if (line.contains(deskName)) {
	                	log.info("line:"+line);
	                    String[] items = line.split("%")[0].split(" ");
	                    int lastIndex = items.length - 1;
	                    double useRateLocal = Double.parseDouble(items[lastIndex].trim());
	                    System.out.println("===>>>"+"磁盘名称："+deskName+"磁盘使用率："+useRateLocal);
	                    Map<String,Object> map= new HashMap<>();
	                    String[] strs = allPath.split("/");
	                    String d= "/"+strs[1]+"/"+strs[2];
	                    log.info("d:"+d);
	                    if(d.equals(line.substring(0,line.indexOf(" ")))) {
	                    	map.put("apath", d);
		                    map.put("space", 100-useRateLocal+"%");
		                    retList.add(map);
	                    }	                    
	                }
	            } 
			}*/
//			ArichiveRet.setList(retList);
			ArichiveRet.setArchiveTime(list.get(0).getArchiveTime());
			ArichiveRet.setEndArchiveTime(list.get(0).getEndArchiveTime());
			ArichiveRet.setPath(path);
			List<ArichiveRet> listRet = new ArrayList<>();
			listRet.add(ArichiveRet);
			response.setCode(ResponseStatusEnum.SUCCESS_CODE.getCode());
			response.setMsg(ResponseStatusEnum.SUCCESS_CODE.getName());
			response.setData(listRet);
		} catch (Exception e) {
			log.error(e);
			response.setCode(ResponseStatusEnum.EXCEPTION.getCode());
			response.setMsg(ResponseStatusEnum.EXCEPTION.getName() + "；" + e.getMessage());
		}
		return response;
	}

	public Integer diskPre(String disk){
		File diskPartition = new File(disk); 		 
		long usableSpace = diskPartition.getUsableSpace(); //可用剩余空间，单位为M 		 
		usableSpace = usableSpace/1024/1024/1024;
		long total = diskPartition.getTotalSpace();
		total = total/1024/1024/1024;
		if(total==0) {
			return 0;
		}
		double use = usableSpace/(double)total;
		return Integer.parseInt(new DecimalFormat("0").format(use*100));
	}
	@Override
	public PageCount queryDataList(UpdateCollectReq req) {
		PageCount pageCount = new PageCount();
		pageCount.setNowPage(req.getNowPage());//当前页
		pageCount.setRowNum(req.getRowNum());//每页多少条
		//查询总条数
		Map<String,Object> datemap = new HashMap<String,Object>();
		
		//TODO 新增机构代码
		datemap.put("businessNo", req.getBusinessNo());//业务号
		datemap.put("appliName", req.getAppliName());//投保人姓名
		datemap.put("organCode", req.getOrganCode());//机构代码
		datemap.put("projson", req.getProjson());//业务数据
		//归档状态
		datemap.put("archiveFlag", req.getArchiveFlag());//归档状态
		//总数
		int allCount = dataCollectMapper.queryCountByBunoAppName(datemap);
		if(0==pageCount.getRowNum()) {
			pageCount.setRowNum(10);
		}
		if(0==pageCount.getNowPage()) {
			pageCount.setNowPage(1);
		}
		int allPages = allCount / pageCount.getRowNum();

		if (allCount % pageCount.getRowNum() > 0) {
			allPages += 1;//总页数
		}
		pageCount.setAllPages(allPages);
		pageCount.setAllCount(allCount);
		int minTotal = (pageCount.getNowPage() - 1) * pageCount.getRowNum();
		int maxTotal = pageCount.getNowPage() * pageCount.getRowNum();
		pageCount.setMinTotal(minTotal);
		pageCount.setMaxTotal(maxTotal);
		pageCount.setMaxminTotal(maxTotal-minTotal);
		pageCount.setObject(datemap);
		List<DataCollect> dataCollectList = dataCollectMapper.queryDataPageByBunoAppName(pageCount);
		List<QueryDataCollectListRes> resList = new ArrayList<QueryDataCollectListRes>();
		for(DataCollect dataCollect:dataCollectList) {
			QueryDataCollectListRes res = new QueryDataCollectListRes();
			SysMaintain maintain = new SysMaintain();
			maintain.setSystemNo(dataCollect.getSysCode());
			BeanUtils.copyProperties(dataCollect, res, QueryDataCollectListRes.class);
			List<SysMaintain> mainList = sysMaintainMapper.querySysMaintain(maintain);
			if(mainList!=null&&mainList.size()>0) {
				res.setSysName(mainList.get(0).getSystemName());//系统名称
			}
			resList.add(res);
		}
		pageCount.setDatas(resList);
		return pageCount;
	}

	

	
}
